<template>
  <div class="container mx-auto px-4 py-8">
    <div v-if="game" class="bg-white rounded-lg shadow-lg overflow-hidden">
      <div class="md:flex">
        <div class="md:w-1/3">
          <img :src="`http://localhost:3000/images/games/${game.image}`" alt="游戏封面" class="w-full h-64 md:h-full object-cover">
        </div>
        <div class="md:w-2/3 p-6">
          <div class="flex justify-between items-start mb-4">
            <h1 class="text-3xl font-bold">{{ game.title }}</h1>
            <button @click="toggleFavorite(game.id)" class="text-red-500 hover:text-red-700 transition-colors">
              <i class="fa fa-heart" :class="isGameFavorited(game.id) ? 'fas' : 'far'"></i>
            </button>
          </div>
          
          <div class="grid grid-cols-2 gap-4 mb-4">
            <div class="text-sm">
              <p class="text-gray-500">发行日期</p>
              <p>{{ game.release_date }}</p>
            </div>
            <div class="text-sm">
              <p class="text-gray-500">游戏类型</p>
              <p>{{ game.genre }}</p>
            </div>
            <div class="text-sm">
              <p class="text-gray-500">平台</p>
              <p>{{ game.platform }}</p>
            </div>
          </div>
          
          <div class="mb-6">
            <h3 class="font-bold text-lg mb-2">游戏介绍</h3>
            <p class="text-gray-600">{{ game.description }}</p>
          </div>
          
          <div class="mt-6">
            <h3 class="font-bold text-lg mb-3">评论 ({{ comments.length }})</h3>
            
            <div v-if="isAuthenticated()" class="mb-6">
              <textarea v-model="newComment" rows="3" class="w-full border border-gray-300 rounded-md p-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="写下你的评论..."></textarea>
              <button @click="addComment" class="mt-2 bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 rounded-md transition-colors">发布评论</button>
            </div>
            <div v-else class="mb-6 p-4 bg-gray-100 rounded-md">
              <p class="text-gray-600">请 <router-link to="/login" class="text-blue-600 hover:underline">登录</router-link> 后发表评论</p>
            </div>
            
            <div v-for="comment in comments" :key="comment.id" class="border-b border-gray-200 pb-4 mb-4">
              <div class="flex items-center mb-2">
                <span class="font-medium mr-2">{{ comment.username }}</span>
                <span class="text-xs text-gray-500">{{ formatDate(comment.created_at) }}</span>
              </div>
              <p class="text-gray-700">{{ comment.content }}</p>
              <div v-if="isAuthenticated() && (getUserId() === comment.user_id || isAdmin())" class="mt-2">
                <button @click="deleteComment(comment.id)" class="text-red-500 hover:text-red-700 text-sm">删除</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-else class="text-center py-16">
      <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mb-4"></div>
      <p>加载中...</p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      game: null,
      comments: [],
      newComment: '',
      favorites: []
    };
  },
  mounted() {
    this.fetchGame();
    this.fetchComments();
    this.fetchFavorites();
  },
  methods: {
    async fetchGame() {
      try {
        const response = await this.axios.get(`/games/${this.$route.params.id}`);
        this.game = response.data;
      } catch (error) {
        console.error(error);
        alert('获取游戏详情失败');
        this.$router.push({ name: 'Home' });
      }
    },
    async fetchComments() {
      try {
        const response = await this.axios.get(`/games/${this.$route.params.id}/comments`);
        this.comments = response.data;
      } catch (error) {
        console.error(error);
        alert('获取评论失败');
      }
    },
    async fetchFavorites() {
      try {
        const response = await this.axios.get('/users/me/favorites');
        this.favorites = response.data.map(game => game.id);
      } catch (error) {
        console.error(error);
      }
    },
    isGameFavorited(gameId) {
      return this.favorites.includes(gameId);
    },
    async toggleFavorite(gameId) {
      if (!this.isAuthenticated()) {
        return this.$router.push({ name: 'Login' });
      }
      
      try {
        if (this.isGameFavorited(gameId)) {
          await this.axios.delete(`/games/${gameId}/favorite`);
          this.favorites = this.favorites.filter(id => id !== gameId);
        } else {
          await this.axios.post(`/games/${gameId}/favorite`);
          this.favorites.push(gameId);
        }
      } catch (error) {
        console.error(error);
        alert('操作失败');
      }
    },
    async addComment() {
      if (!this.newComment.trim()) {
        return alert('评论内容不能为空');
      }
      
      try {
        await this.axios.post(`/games/${this.$route.params.id}/comments`, {
          content: this.newComment
        });
        
        this.fetchComments();
        this.newComment = '';
      } catch (error) {
        console.error(error);
        alert('发布评论失败');
      }
    },
    async deleteComment(commentId) {
      if (!confirm('确定要删除这条评论吗？')) {
        return;
      }
      
      try {
        await this.axios.delete(`/comments/${commentId}`);
        this.fetchComments();
      } catch (error) {
        console.error(error);
        alert('删除评论失败');
      }
    },
    isAuthenticated() {
      return localStorage.getItem('token');
    },
    getUserId() {
      const user = JSON.parse(localStorage.getItem('user'));
      return user ? user.id : null;
    },
    isAdmin() {
      const user = JSON.parse(localStorage.getItem('user'));
      return user ? user.isAdmin : false;
    },
    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toLocaleDateString();
    }
  }
};
</script>  